package org.belkodevelop.admin.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.belkodevelop.admin.dao.AdminDAO;
import org.belkodevelop.mail.Mail;
import org.belkodevelop.mail.MailTemplate;
import org.belkodevelop.mail.SimpleMailSender;
import org.belkodevelop.role.RoleConstants;
import org.belkodevelop.user.domain.User;
import org.belkodevelop.user.exception.ErrorSendMail;
import org.belkodevelop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminService {

    private final Log log = LogFactory.getLog(getClass());

    @Autowired
    private AdminDAO adminDAO;

    @Autowired
    MailTemplate registrationDoctorSuccessMailTemplate;

    @Autowired
    MailTemplate registrationDoctorFailMailTemplate;

    @Autowired
    private SimpleMailSender mailSender;

    @Autowired
    private UserService userSerivce;

    @Transactional
    public boolean confirmRegistration(long userId, User admin) {
        if (admin.getRoles().contains(RoleConstants.ADMIN_ROLE)) {
            adminDAO.enableUser(userId);

            User user = userSerivce.getUserById(userId);

            Mail mail = registrationDoctorSuccessMailTemplate.createMail(user.getEmail());
            try {
                mailSender.send(mail);
            } catch (Exception ex) {
                log.warn("Error sending mail!", ex);
                throw new ErrorSendMail(ex);
            }
            return true;
        }
        return false;
    }

    @Transactional
    public boolean rejectRegistration(long userId, User admin) {
        if (admin.getRoles().contains(RoleConstants.ADMIN_ROLE)) {
            User user = userSerivce.getUserById(userId);
            adminDAO.removeUser(userId);

            Mail mail = registrationDoctorFailMailTemplate.createMail(user.getEmail());
            try {
                mailSender.send(mail);
            } catch (Exception ex) {
                log.warn("Ignore error sending mail.", ex);
            }
            return true;
        }
        return false;
    }

    @Transactional
    public void removeUser(long userId, User admin) {
        if (admin.getRoles().contains(RoleConstants.ADMIN_ROLE)) {
            adminDAO.removeUser(userId);
        }
    }

    @Transactional
    public void disableUser(long userId, User admin) {
        if (admin.getRoles().contains(RoleConstants.ADMIN_ROLE)) {
            adminDAO.disableUser(userId);
        }
    }

    @Transactional
    public void enableUser(long userId, User admin) {
        if (admin.getRoles().contains(RoleConstants.ADMIN_ROLE)) {
            adminDAO.enableUser(userId);
        }
    }
}
